import { GameMode, Player } from "@minecraft/server";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { Game, GameComponent } from "@sapi-game/main";
import { PKParkourState } from "../pkParkourState";
import { PKItemStoreComponent } from "./itemStrore";

export class PKGameOverController extends GameComponent<PKParkourState> {
    private remainingLives = 0;
    private isEnded = false;

    override onAttach(): void {
        this.remainingLives = this.context.config.lifeCount;

        const timer = this.state.getComponent(Timer);
        this.subscribe(timer.events.onTime, this.onTimeUp.bind(this), { time: 0 });

        //踩钻石块就赢
        this.subscribe(
            Game.events.onBlock,
            (t) => {
                if (
                    this.state.team.getById(t.player.id) &&
                    t.player.getGameMode() !== GameMode.Spectator &&
                    !this.isEnded
                ) {
                    this.onWin();
                }
            },
            { group: this.state.team, typeIds: ["minecraft:diamond_block"] }
        );
    }

    /**时间到 */
    onTimeUp() {
        if (this.isEnded) return;
        this.runner.run(async (r) => {
            this.context.groupSet.title("时间到");
            this.isEnded = true;
            await r.wait(20);
            r.do(() => this.state.onLose());
        });
    }

    /**死了 */
    onDie(player: Player) {
        //传送到开始点位
        const store = this.state.getComponent(PKItemStoreComponent);
        store.storeItem(player);
        player.runCommand("clear @s");
        if (this.isEnded) return;
        this.remainingLives--;

        if (this.remainingLives <= 0) {
            this.context.groupSet.title("没命了");
            this.runner.runDelay(() => {
                this.state.onLose();
            }, 40);
            this.isEnded = true;
            return;
        }
        this.context.groupSet.title(`剩余 ${this.remainingLives} 次机会`);
    }

    onWin() {
        if (this.isEnded) return;
        this.context.groupSet.title(`${this.state.isBlue ? "蓝" : "红"}队通过了跑酷`);
        this.isEnded = true;
        this.state.onWin();
    }
}
